<template>
  <div class="jsbos-common-layout">
    <div class="jsbos-common-layout-center">
      <el-row class="jsbos-common-search-box" :gutter="16">
        <el-form @submit.native.prevent>
          <el-col :span="4">
            <el-form-item label="考试名称">
              <el-input
                v-model="query.fullName"
                placeholder="请输入"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="状态">
              <el-select
                v-model="query.enabledMark"
                placeholder="请选择"
                clearable
              >
                <el-option
                  v-for="(item, index) in enabledMarkOptions"
                  :key="index"
                  :label="item.fullName"
                  :value="item.id"
                  :disabled="item.disabled"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="开始时间">
              <el-date-picker
                v-model="query.startDatetime"
                type="datetimerange"
                value-format="timestamp"
                format="yyyy-MM-dd HH:mm:ss"
                :picker-options="pickerOptions"
                :default-time="['08:00:00', '24:00:00']"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <template v-if="showAll">
            <el-col :span="4">
              <el-form-item label="创建用户">
                <userSelect
                  v-model="query.creatorUserId"
                  placeholder="请选择"
                />
              </el-form-item>
            </el-col>
          </template>
          <el-col :span="6">
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" @click="search()"
                >查询</el-button
              >
              <el-button icon="el-icon-refresh-right" @click="reset()"
                >重置</el-button
              >
              <el-button
                type="text"
                icon="el-icon-arrow-down"
                @click="showAll = true"
                v-if="!showAll"
              >
                展开
              </el-button>
              <el-button
                type="text"
                icon="el-icon-arrow-up"
                @click="showAll = false"
                v-else
              >
                收起
              </el-button>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <div class="jsbos-common-layout-main jsbos-flex-main">
        <div class="jsbos-common-head">
          <div></div>
          <div class="jsbos-common-head-right">
            <el-tooltip effect="dark" content="刷新" placement="top">
              <el-link
                icon="icon-ym icon-ym-Refresh JSBOS-common-head-icon"
                :underline="false"
                @click="reset()"
              />
            </el-tooltip>
            <screen-full isContainer />
            <el-tooltip effect="dark" content="列设置" placement="top">
              <el-link
                icon="icon-ym icon-ym-options jsbos-common-head-icon"
                :underline="false"
                @click="() => this.$refs.jsbosTableRef.showDrawer()"
              />
            </el-tooltip>
          </div>
        </div>
        <jsbos-table
          v-loading="listLoading"
          :data="list"
          ref="jsbosTableRef"
          @sort-change="sortChange"
        >
          <el-table-column
            prop="fullName"
            label="考试名称"
            min-width="200"
            align="left"
          />
          <el-table-column
            prop="startDatetime"
            label="开始时间"
            width="150"
            align="left"
          />
          <el-table-column
            prop="endDatetime"
            label="截至时间"
            width="150"
            align="left"
          />
          <el-table-column
            label="可见范围"
            width="100"
            prop="examScope"
            algin="left"
          >
            <template slot-scope="scope">
              {{ scope.row.examScope | dynamicText(examScopeOptions) }}
            </template>
          </el-table-column>

          <el-table-column
            prop="examUserCount"
            label="安排人数"
            width="150"
            align="left"
          />
          <el-table-column
            prop="examingUserCount"
            label="参训人数"
            width="150"
            align="left"
          />
          <el-table-column
            prop="examPassUserCount"
            label="通过人数"
            width="150"
            align="left"
          />
          <el-table-column
            prop="ExamUserRate"
            label="通过率"
            width="150"
            align="left"
          >
            <template
              slot-scope="scope"
              v-if="
                isFinite(
                  (scope.row.examPassUserCount / scope.row.examUserCount) * 100
                )
              "
            >
              {{
                (
                  (scope.row.examPassUserCount / scope.row.examUserCount) *
                  100
                ).toFixed(2) | numberFormat("0.00")
              }}%
            </template>
          </el-table-column>
          <el-table-column
            prop="creatorUserId"
            label="创建用户"
            width="100"
            align="left"
          />
          <el-table-column
            prop="creatorTime"
            label="创建时间"
            width="150"
            align="left"
          />
          <el-table-column
            label="状态"
            width="100"
            prop="enabledMark"
            algin="left"
          >
            <template slot-scope="scope">
              {{ scope.row.enabledMark | dynamicText(enabledMarkOptions) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200">
            <template slot-scope="scope">
              <el-button type="text" @click.native="goDataDetail(scope.row.id)"
                >数据
              </el-button>
            </template>
          </el-table-column>
        </jsbos-table>
        <pagination
          :total="total"
          :page.sync="listQuery.currentPage"
          :limit.sync="listQuery.pageSize"
          @pagination="initData"
        />
      </div>
    </div>
    <ExportBox v-if="exportBoxVisible" ref="ExportBox" @download="download" />
    <ExamData
      v-if="dataDetailVisible"
      ref="examDataDetail"
      @refresh="dataDetailVisible = false"
    />
  </div>
</template>

<script>
import { getList, Delete, getReportList } from "@/views/exam/api/manager";
import request from "@/utils/request";
import JSBOSForm from "./Form";
import ExportBox from "./ExportBox";
import Detail from "./Detail";
import UpdateScope from "./UpdateScope";
import QRCode from "qrcodejs2";
import ExamData from "./ExamData";

export default {
  name: "TemsExamManager",
  components: { ExportBox, ExamData },
  data() {
    return {
      dataDetailVisible: false,
      sysAddress: "",
      httpCourseMUrl: "",

      showAll: false,
      scopeVisible: false,
      detailVisible: false,
      query: {
        fullName: undefined,
        enabledMark: undefined,
        startDatetime: undefined,
        creatorUserId: undefined,
      },
      treeProps: {
        children: "children",
        label: "fullName",
        value: "id",
      },
      list: [],
      listLoading: true,
      total: 0,
      listQuery: {
        currentPage: 1,
        pageSize: 20,
        sort: "desc",
        sidx: "",
      },
      formVisible: false,
      exportBoxVisible: false,
      columnList: [
        { prop: "fullName", label: "考试名称" },
        { prop: "examPaperId", label: "试卷名称" },
        { prop: "startDatetime", label: "开始时间" },
        { prop: "endDatetime", label: "截至时间" },
        { prop: "examScope", label: "可见范围" },
        { prop: "creatorUserId", label: "创建用户" },
        { prop: "creatorTime", label: "创建时间" },
        { prop: "enabledMark", label: "状态" },
      ],
      categoryIdOptions: [
        {
          children: [{ fullName: "选项1-1", id: "2" }],
          fullName: "选项1",
          id: "1",
        },
      ],
      categoryIdProps: {
        label: "fullName",
        value: "id",
        children: "children",
      },
      examRepeatTypeOptions: [
        { fullName: "考试结束前无限制重考", id: "before" },
        { fullName: "自定义重考次数", id: "custom" },
      ],
      examRepeatTypeProps: {
        label: "fullName",
        value: "id",
      },
      examAnswersOptions: [
        { fullName: "交卷后", id: "submitAfter" },
        {
          fullName: "及格后",
          id: "passAfter",
        },
        { fullName: "考试结束后", id: "examAfter" },
        { fullName: "不允许查看", id: "notAllow" },
      ],
      examAnswersProps: {
        label: "fullName",
        value: "id",
      },
      examScopeOptions: [
        { fullName: "全公司", id: "all" },
        { fullName: "仅创建人", id: "creator" },
        {
          fullName: "部门/人员",
          id: "selectScope",
        },
      ],
      examScopeProps: {
        label: "fullName",
        value: "id",
      },
      enabledMarkOptions: [
        { fullName: "草稿", id: "0" },
        { fullName: "发布", id: "1" },
      ],
      enabledMarkProps: {
        label: "fullName",
        value: "id",
      },
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
    };
  },
  computed: {
    menuId() {
      return this.$route.meta.modelId || "";
    },
  },
  created() {
    this.initData();
  },
  methods: {
    goDataDetail(id) {
      this.dataDetailVisible = true;
      this.$nextTick(() => {
        this.$refs.examDataDetail.init(id);
      });
    },
    goDetail(id) {
      this.detailVisible = true;
      this.$nextTick(() => {
        this.$refs.Detail.init(id);
      });
    },
    sortChange({ column, prop, order }) {
      this.listQuery.sort = order == "ascending" ? "asc" : "desc";
      this.listQuery.sidx = !order ? "" : prop;
      this.initData();
    },
    initData() {
      this.listLoading = true;
      let _query = {
        ...this.listQuery,
        ...this.query,
        menuId: this.menuId,
      };
      getReportList(_query).then((res) => {
        var _list = [];
        for (let i = 0; i < res.data.list.length; i++) {
          let _data = res.data.list[i];
          _list.push(_data);
        }
        this.list = _list;
        this.total = res.data.pagination.total;

        this.listLoading = false;
      });
    },
    handleDel(id) {
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        type: "warning",
      })
        .then(() => {
          Delete(id).then((res) => {
            this.$message({
              type: "success",
              message: res.msg,
              onClose: () => {
                this.initData();
              },
            });
          });
        })
        .catch(() => {});
    },
    addOrUpdateHandle(id, isDetail) {
      this.formVisible = true;
      this.$nextTick(() => {
        this.$refs.JSBOSForm.init(id, isDetail);
      });
    },
    handleUpdateScope(id) {
      this.scopeVisible = true;
      this.$nextTick(() => {
        this.$refs.updateScope.init(id);
      });
    },
    handleUnpublish(id) {
      this.$confirm(
        "取消发布后学员在学习界面将看不到当前考试了，确定要取消发布吗？",
        "提示",
        {
          type: "warning",
        }
      )
        .then(() => {
          request({
            url: `/api/exam/TemsExam/unpublish/${id}`,
            method: "PUT",
          }).then((res) => {
            this.$message({
              type: "success",
              message: res.msg,
              onClose: () => {
                this.initData();
              },
            });
          });
        })
        .catch(() => {});
    },
    exportData() {
      this.exportBoxVisible = true;
      this.$nextTick(() => {
        this.$refs.ExportBox.init(this.columnList);
      });
    },
    download(data) {
      let query = {
        ...data,
        ...this.listQuery,
        ...this.query,
        menuId: this.menuId,
      };
      request({
        url: `/api/exam/TemsExam/Actions/Export`,
        method: "GET",
        data: query,
      }).then((res) => {
        if (!res.data.url) return;
        this.jsbos.downloadFile(res.data.url);
        this.$refs.ExportBox.visible = false;
        this.exportBoxVisible = false;
      });
    },
    search() {
      this.initData();
    },
    refresh(isrRefresh) {
      this.formVisible = false;
      if (isrRefresh) this.reset();
    },
    resetListQuery() {
      this.listQuery = {
        keyword: "",
        currentPage: 1,
        pageSize: 20,
        sort: "asc",
        sidx: "",
      };
    },
    resetQuery() {
      for (let key in this.query) {
        this.query[key] = undefined;
      }
    },
    reset() {
      this.resetListQuery();
      this.resetQuery();
      this.search();
    },
    createQrcode(row) {
      this.qrcodeVisible = true;
      if (!row) {
        return;
      }
      this.qrDialogName = "【" + row.fullName + "】课程二维码";
      const baseUrl = this.sysAddress.substring(
        0,
        this.sysAddress.indexOf("#")
      );
      this.httpCourseMUrl = baseUrl + "/#/pages/examWeb/index?id=" + row.id;
      this.$nextTick(() => {
        const qrCodeRef = this.$refs["qrCode"];
        if (qrCodeRef) {
          qrCodeRef.innerHTML = ""; // 清空二维码容器
          new QRCode(qrCodeRef, {
            width: 300,
            height: 300,
            text: this.httpCourseMUrl,
            correctLevel: QRCode.CorrectLevel.M,
          });
          let qrcodeCanvas =
            this.$refs.qrCode.getElementsByTagName("canvas")[0];
          this.qrcodeImgUrl = qrcodeCanvas.toDataURL("image/png"); // 作为下载图片资源
        } else {
          console.error("QRCode ref is not defined");
        }
      });
    },
    // 下载二维码
    downQrcodeImg() {
      let downloadLink = this.$refs.downLoadImgUrl;
      downloadLink.setAttribute("href", this.qrcodeImgUrl);
      downloadLink.setAttribute(
        "download",
        `${this.qrDialogName}_${new Date().getTime()}.png`
      );
      downloadLink.click();
      URL.revokeObjectURL(downloadLink.href);
      this.qrcodeVisible = false;
    },
  },
};
</script>
<style>
.qr_create {
  width: 100%;
  display: flex;
  justify-content: center;
}
.qr_create_httpUrl {
  width: 100%;
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}

.el-dropdown-link {
  cursor: pointer;
  color: #409eff;
}
.el-icon-arrow-down,
.el-dropdown-link {
  font-size: 12px;
}
</style>
